package com.example.flutter_world_cup

import android.os.Handler
import android.os.Looper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.EventChannel

class FlutterWorldCupPlugin : FlutterPlugin, EventChannel.StreamHandler {
    private val countries = listOf(
        "Russia 2018", "Brazil 2014", "South Africa 2010", "Germany 2006",
        "South Korea/Japan 2002", "France 1998", "USA 1994"
    )
    private var index = 0
    private lateinit var eventSink: EventChannel.EventSink
    private val handler = Handler(Looper.getMainLooper())

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        val eventChannel = EventChannel(binding.binaryMessenger, "com.example.world_cup/countries")
        eventChannel.setStreamHandler(this)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {}

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        this.eventSink = events!!
        startSendingCountries()
    }

    override fun onCancel(arguments: Any?) {
        handler.removeCallbacksAndMessages(null) // 停止发送
    }

    private fun startSendingCountries() {
        handler.postDelayed(object : Runnable {
            override fun run() {
                if (index < countries.size) {
                    eventSink.success(countries[index])
                    index++
                    handler.postDelayed(this, 1000) // 每秒发送一次
                } else {
                    eventSink.endOfStream()
                }
            }
        }, 1000) // 首次延迟1秒
    }
}